home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
ftp.cs.arizona.edu
/
ftp.cs.arizona.edu.tar
/
ftp.cs.arizona.edu
/
icon
/
newsgrp
/
group99a.txt
/
000109_icon-group-sender _Tue May 4 15:02:32 1999.msg
< prev
next >
Wrap
Internet Message Format
|
2000-09-20
|
3KB
Return-Path: <icon-group-sender>
Received: (from root@localhost)
by baskerville.CS.Arizona.EDU (8.9.1a/8.9.1) id OAA23035
for icon-group-addresses; Tue, 4 May 1999 14:58:09 -0700 (MST)
Message-Id: <199905042158.OAA23035@baskerville.CS.Arizona.EDU>
Delivered-To: icon-group@cs.arizona.edu
To: icon-group@optima.CS.Arizona.EDU
Date: 4 May 1999 13:45:16 -0500
From: msglass@MCS.COM (Michael Glass)
Subject: Digit Sort Worst Algorithm
Errors-To: icon-group-errors@optima.CS.Arizona.EDU
Status: RO
I just read the article on the digit sort problem in April _Icon Analyst_.
I apologize for posting solution #17 sans explanation. I was having fun
trying to write a DIFFERENT (not BETTER) solution. I knew it was awful and
should have said something.
The algorithm is O(n^4). It works (conceptually) like this:
# Let D[1] ... D[n] be an array of digits called by value
procedure P(D)
if there exist i,j such that D[i] and D[j] are out of order
then
return P(D with the i and j digits swapped)
else
return D
Since finding two digits to swap is O(n^2), and this thing calls
itself up to O(n^2) times, the worst case performance is O(n^4).
In words, it is imitating something like an exchange or bubble sort.
The difference is that after every swap, the indices START AGAIN FROM THE
BEGINNING looking for new elements to swap. So finding the NEXT pair of
elements to swap is O(n^2).
A non-recursive version would look like this:
for j := 2 to n
for i := 1 to j-1
if D[i] > D[j] then {
swap D[i] and D[j]
i := 1 # The recursive call forces
j := 1 # the indices to start at the beginning
}
Digits are swapped by arithmetic. Suppose you have 7830 and you want
to swap the 7 with the the 3. The difference 7 - 3 = 4, so you can
subtract 4000 (converting 7000 to 3000) and add 40 (converting 30 to 70):
7830 - 4000 + 40 = 3870
This is accomplished in the usual way of raising 10 to the powers
of digit positions.
Further inefficiency comes from the fact that the sort is performed
on a string of digits and the arithmetic is performed on the number. Since
the base representation is the number, the number-to-string conversion is
really overdone.
By the way, I thought there was a kind of sick beauty in using
goal-directed evaluation and tail recursion to produce a two line sort.
Probably it comes from having taught the undergraduate algorithms class
a few times. You start finding beauty in the darndest algorithms, even if
they take the worst performance in the book and square it.
But there was someting about 25 days of compute time that really took
the shine off of it.
-- Michael Glass